package com.mdd.admin.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.admin.LikeAdminThreadLocal;
import com.mdd.admin.service.IPrinterService;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.validate.shop.PrinterValidate;
import com.mdd.admin.vo.shop.PrinterVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.article.Article;
import com.mdd.common.entity.shop.Printer;
import com.mdd.common.enums.PrintEnum;
import com.mdd.common.mapper.shop.PrinterMapper;
import com.mdd.common.util.HttpUtils;
import com.mdd.common.util.TimeUtils;
import me.chanjar.weixin.common.util.crypto.SHA1;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class PrinterServiceImpl implements IPrinterService {
    @Resource
    private PrinterMapper printerMapper;

    @Override
    public PageResult<PrinterVo> list(PageValidate pageValidate) {
        Integer pageNo   = pageValidate.getPageNo();
        Integer pageSize = pageValidate.getPageSize();
        Integer aid = LikeAdminThreadLocal.getAdminId();

        IPage<Printer> page = new Page<>(pageNo,pageSize);
        QueryWrapper<Printer> eq = new QueryWrapper<Printer>().eq("aid", aid).eq("is_delete", 0);
        eq.orderByDesc("create_time");
        IPage<Printer> data = printerMapper.selectPage(page, eq);
        List<Printer> records = data.getRecords();
        List<PrinterVo> printerVos = new ArrayList<>();
        for (Printer printer : records){
            PrinterVo printerVo = new PrinterVo();
            BeanUtils.copyProperties(printer,printerVo);
            printerVos.add(printerVo);
        }
        return PageResult.pageHelper(printerVos);
    }

    @Override
    public void add(PrinterValidate printerValidate) {
        Printer printer = new Printer();
        BeanUtils.copyProperties(printerValidate,printer);
        printer.setAid(LikeAdminThreadLocal.getAdminId());
        printer.setCreateTime(TimeUtils.timestamp());
        printer.setLastUpdateTime(TimeUtils.timestamp());
        printerMapper.insert(printer);

//        String url = "https://open.xpyun.net/api/openapi/xprinter/addPrinters";
        String url = "https://gm.open.xpyun.net/api/openapi/xprinter/addPrinters";
        sycPrint(printer, url,"add");


    }

    private void sycPrint(Printer printer, String url,String type) {
        JSONObject jsonObject = new JSONObject();
        String  user = "306132416@qq.com";
        long timestamp = Instant.now().getEpochSecond();
        String userkey = "d6418389641b417ca7078f531e7be86a";
        String  sign = String.format("%s%s%s",user,userkey,timestamp);

        String gen = SHA1.gen(sign);

        jsonObject.put("user",user);
        jsonObject.put("timestamp",timestamp);
        jsonObject.put("sign",gen);
        // debug=1返回非json格式的数据，仅测试时候使用
        jsonObject.put("debug","0");
        if("add".equals(type)){
            JSONObject item = new JSONObject();
            // 打印机名称
            item.put("name",printer.getName());
            // 打印机编号
            item.put("sn",printer.getSecret());
            JSONArray items = new JSONArray();
            items.add(item);
            jsonObject.put("items",items);
        }else{
            jsonObject.put("name",printer.getName());
            jsonObject.put("sn",printer.getSecret());
        }
        System.out.println(jsonObject.toJSONString());
        String s = HttpUtils.sendPost(url, jsonObject.toJSONString());

        System.out.println(s);

        JSONObject ret = JSONObject.parseObject(s);
        PrintEnum[] values = PrintEnum.values();
        for (PrintEnum code : values) {
            String code1 = code.getCode();
            if(code1.equals(ret.getString("code"))){
                Assert.isTrue("0".equals(ret.getString("code")),"zh".equals(LikeAdminThreadLocal.get("defaultLanguage"))?code.getMsgZh():code.getMsgRu());
            }
        }
        Assert.isTrue("0".equals(ret.getString("code")),ret.getString("msg"));
    }

    @Override
    public PrinterVo detail(Integer id) {
        Assert.notNull(id,"参数错误");
        Printer printer = printerMapper.selectById(id);
        PrinterVo printerVo = new PrinterVo();
        BeanUtils.copyProperties(printer,printerVo);
        return printerVo;
    }

    @Override
    public void delete(Integer id) {
        Assert.notNull(id,"参数错误");
        Printer printer = printerMapper.selectById(id);
//        String url ="https://open.xpyun.net/api/openapi/xprinter/delPrinters";
        String url ="https://gm.open.xpyun.net/api/openapi/xprinter/delPrinters";

        JSONObject jsonObject = new JSONObject();
        String  user = "306132416@qq.com";
        long timestamp = Instant.now().getEpochSecond();
        String userkey = "d6418389641b417ca7078f531e7be86a";
        String  sign = String.format("%s%s%s",user,userkey,timestamp);

        String gen = SHA1.gen(sign);

        jsonObject.put("user",user);
        jsonObject.put("timestamp",timestamp);
        jsonObject.put("sign",gen);
        jsonObject.put("debug","0");
        jsonObject.put("snlist",new String[]{printer.getSecret()});


        String s = HttpUtils.sendPost(url, jsonObject.toJSONString());

        System.out.println(s);

        JSONObject ret = JSONObject.parseObject(s);
        PrintEnum[] values = PrintEnum.values();
        for (PrintEnum code : values) {
            String code1 = code.getCode();
            if(code1.equals(ret.getString("code"))){
                Assert.isTrue("0".equals(ret.getString("code")),"zh".equals(LikeAdminThreadLocal.get("defaultLanguage"))?code.getMsgZh():code.getMsgRu());
            }
        }
        Assert.isTrue("0".equals(ret.getString("code")),ret.getString("msg"));
        printer.setDeleteTime(TimeUtils.timestamp());
        printer.setIsDelete(1);
        printerMapper.updateById(printer);


    }

    @Override
    public void edit(Printer printerValidate) {
        Printer printer = new Printer();
        BeanUtils.copyProperties(printerValidate,printer);
        printer.setLastUpdateTime(TimeUtils.timestamp());
        printerMapper.editPrint(printer);
//        String url = "https://open.xpyun.net/api/openapi/xprinter/updPrinter";
        String url = "https://gm.open.xpyun.net/api/openapi/xprinter/updPrinter";
        sycPrint(printer, url,"edit");
    }

    @Override
    public void change(Integer id) {
        Printer print = printerMapper.selectOne(
                new QueryWrapper<Printer>()
                        .select("id,status")
                        .eq("id", id)
                        .eq("is_delete", 0));

        Integer status=print.getStatus()==0?1:0;
        printerMapper.changePrintStatus(id,status);
    }


    public static String SHA1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest
                    .getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static void main(String[] args) {
//        String url = "https://open.xpyun.net/api/openapi/xprinter/delPrinters";
//        JSONObject jsonObject = new JSONObject();
//        String  user = "306132416@qq.com";
//        long timestamp = Instant.now().getEpochSecond();
//        String userkey = "d6418389641b417ca7078f531e7be86a";
//        String  sign = String.format("%s%s%s",user,userkey,timestamp);
//
//        String gen = SHA1.gen(sign);
//
//        jsonObject.put("user",user);
//        jsonObject.put("timestamp",timestamp);
//        jsonObject.put("sign",gen);
//        jsonObject.put("debug","0");
//        jsonObject.put("snlist",new String[]{"747S467W6ACB649"});
//
//        System.out.println(jsonObject.toJSONString());
//
//        String s = HttpUtils.sendPost(url, jsonObject.toJSONString());
// modeInfo/print01
        String s1 = TimeUtils.timestampToDate(System.currentTimeMillis() / 1000);
        System.out.println(s1);

    }
}
